﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Linq.Expressions;
using JavascriptEngine.Runtime;

namespace JavascriptEngine.Compiler
{
    public class ContextFrame
    {
        public ContextFrame Parent { get; set; }
        public IDictionary<string, ParameterExpression> Variables { get; private set; }
        public LabelTarget ReturnLabel { get; set;}

        public ContextFrame()
        {
            Variables = new Dictionary<string, ParameterExpression>();
            Parent = null;
        }

        public ParameterExpression LookUp(string variableName)
        {
            ParameterExpression param;
            if (Variables.TryGetValue(variableName, out param))
                return param;
            if (Parent != null)
                return Parent.LookUp(variableName);
            return null;
        }

        public ContextFrame(ContextFrame parent)
            : this()
        {
            Parent = parent;
        }

        internal ParameterExpression Add(string variableName)
        {
            ParameterExpression param = Expression.Parameter(typeof(JavaScriptObject), variableName);
            Variables.Add(variableName, param);
            return param;
        }

        internal void Add(string variableName, ParameterExpression variable)
        {
            Variables.Add(variableName, variable);
        }
    }
}
